/*
 * Copyright © 2014 Broadcom
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * @file vc4_formats.c
 *
 * Contains the table and accessors for VC4 texture and render target format
 * support.
 *
 * The hardware has limited support for texture formats, and extremely limited
 * support for render target formats.  As a result, we emulate other formats
 * in our shader code, and this stores the table for doing so.
 */

#include "util/format/u_format.h"
#include "util/macros.h"

#include "vc4_private.h"
#include "vk_format_info.h"
#include "vc4_vk_formats.h"
#include "kernel/vc4_packet.h"

#include "vk_util.h"
#include "drm_fourcc.h"

#define RT_NO        0
#define RT_RGBA8888  1
#define RT_RGB565    2

#define SWIZ(x,y,z,w) {          \
        PIPE_SWIZZLE_##x, \
        PIPE_SWIZZLE_##y, \
        PIPE_SWIZZLE_##z, \
        PIPE_SWIZZLE_##w  \
}

#define FORMAT(pipe, rt, tex, swiz)                                     \
        [PIPE_FORMAT_##pipe] = { true, RT_##rt, VC4_TEXTURE_TYPE_##tex, swiz }

static const struct vc4_format vc4_format_table[] = {
        FORMAT(R8G8B8A8_UNORM, RGBA8888, RGBA8888, SWIZ(X, Y, Z, W)),
        FORMAT(R8G8B8X8_UNORM, RGBA8888, RGBA8888, SWIZ(X, Y, Z, 1)),
        FORMAT(R8G8B8A8_SRGB,  RGBA8888, RGBA8888, SWIZ(X, Y, Z, W)),
        FORMAT(R8G8B8X8_SRGB,  RGBA8888, RGBA8888, SWIZ(X, Y, Z, 1)),

        FORMAT(B8G8R8A8_UNORM, RGBA8888, RGBA8888, SWIZ(Z, Y, X, W)),
        FORMAT(B8G8R8X8_UNORM, RGBA8888, RGBA8888, SWIZ(Z, Y, X, 1)),
        FORMAT(B8G8R8A8_SRGB, RGBA8888, RGBA8888, SWIZ(Z, Y, X, W)),
        FORMAT(B8G8R8X8_SRGB, RGBA8888, RGBA8888, SWIZ(Z, Y, X, 1)),

        FORMAT(B5G6R5_UNORM, RGB565, RGB565, SWIZ(X, Y, Z, 1)),

        FORMAT(ETC1_RGB8, NO, ETC1, SWIZ(X, Y, Z, 1)),

        /* Depth sampling will be handled by doing nearest filtering and not
         * unpacking the RGBA value.
         */
        FORMAT(S8_UINT_Z24_UNORM, NO, RGBA8888, SWIZ(X, Y, Z, W)),
        FORMAT(Z24_UNORM_S8_UINT, NO, RGBA8888, SWIZ(X, Y, Z, W)),
        FORMAT(X8Z24_UNORM,       NO, RGBA8888, SWIZ(X, Y, Z, W)),

        FORMAT(B4G4R4A4_UNORM, NO, RGBA4444, SWIZ(Y, Z, W, X)),
        FORMAT(B4G4R4X4_UNORM, NO, RGBA4444, SWIZ(Y, Z, W, 1)),

        FORMAT(A1B5G5R5_UNORM, NO, RGBA5551, SWIZ(X, Y, Z, W)),
        FORMAT(X1B5G5R5_UNORM, NO, RGBA5551, SWIZ(X, Y, Z, 1)),

        FORMAT(A8_UNORM, NO, ALPHA, SWIZ(0, 0, 0, W)),
        FORMAT(L8_UNORM, NO, ALPHA, SWIZ(W, W, W, 1)),
        FORMAT(I8_UNORM, NO, ALPHA, SWIZ(W, W, W, W)),
        FORMAT(R8_UNORM, NO, ALPHA, SWIZ(W, 0, 0, 1)),

        FORMAT(L8A8_UNORM, NO, LUMALPHA, SWIZ(X, X, X, W)),
        FORMAT(R8G8_UNORM, NO, LUMALPHA, SWIZ(X, W, 0, 1)),
};

static const struct vc4_format *
get_format(VkFormat f)
{
        enum pipe_format format = vk_format_to_pipe_format(f);

        if (format >= ARRAY_SIZE(vc4_format_table) ||
            !vc4_format_table[format].supported)
                return NULL;
        else
                return &vc4_format_table[format];
}

static const struct vc4_format *
get_pipe_format(enum pipe_format format)
{
        if (format >= ARRAY_SIZE(vc4_format_table) ||
            !vc4_format_table[format].supported)
                return NULL;
        else
                return &vc4_format_table[format];
}

bool
vc4_rt_format_supported(VkFormat f)
{
        const struct vc4_format *vf = get_format(f);

        if (!vf)
                return false;

        return vf->rt_type != RT_NO;
}

bool
vc4_rt_format_is_565(VkFormat f)
{
        const struct vc4_format *vf = get_format(f);

        if (!vf)
                return false;

        return vf->rt_type == RT_RGB565;
}

bool
vc4_tex_format_supported(VkFormat f)
{
        const struct vc4_format *vf = get_format(f);

        return vf != NULL;
}

uint8_t
vc4_get_tex_format(VkFormat f)
{
        const struct vc4_format *vf = get_format(f);

        if (!vf)
                return 0;

        return vf->tex_type;
}

const uint8_t *
vc4_get_vkformat_swizzle(VkFormat f)
{
        const struct vc4_format *vf = get_format(f);
        static const uint8_t fallback[] = {0, 1, 2, 3};

        if (!vf)
                return fallback;

        return vf->swizzle;
}

const uint8_t *
vc4_get_format_swizzle(enum pipe_format format)
{
        const struct vc4_format *vf = get_pipe_format(format);
        static const uint8_t fallback[] = {0, 1, 2, 3};

        if (!vf)
                return fallback;

        return vf->swizzle;
}

const struct vc4_format *
vc4_get_format(VkFormat f)
{
    return get_format(f);
}

// bool vc4_supports_tex_format(const struct vc4_device_info *devinfo,
//                                   uint32_t tex_format)
// {
//    assert(devinfo->ver >= 41);

//    switch (tex_format)
//    {
//    case TEXTURE_DATA_FORMAT_R8:
//    case TEXTURE_DATA_FORMAT_R8_SNORM:
//    case TEXTURE_DATA_FORMAT_RG8:
//    case TEXTURE_DATA_FORMAT_RG8_SNORM:
//    case TEXTURE_DATA_FORMAT_RGBA8:
//    case TEXTURE_DATA_FORMAT_RGBA8_SNORM:
//    case TEXTURE_DATA_FORMAT_RGB565:
//    case TEXTURE_DATA_FORMAT_RGBA4:
//    case TEXTURE_DATA_FORMAT_RGB5_A1:
//    case TEXTURE_DATA_FORMAT_RGB10_A2:
//    case TEXTURE_DATA_FORMAT_R16:
//    case TEXTURE_DATA_FORMAT_R16_SNORM:
//    case TEXTURE_DATA_FORMAT_RG16:
//    case TEXTURE_DATA_FORMAT_RG16_SNORM:
//    case TEXTURE_DATA_FORMAT_RGBA16:
//    case TEXTURE_DATA_FORMAT_RGBA16_SNORM:
//    case TEXTURE_DATA_FORMAT_R16F:
//    case TEXTURE_DATA_FORMAT_RG16F:
//    case TEXTURE_DATA_FORMAT_RGBA16F:
//    case TEXTURE_DATA_FORMAT_R11F_G11F_B10F:
//    case TEXTURE_DATA_FORMAT_R4:
//       return true;
//    default:
//       return false;
//    }
// }

// static enum vc4_texture_data_type
// get_image_texture_format(struct vc4_image *image)
// {
//         uint8_t format = vc4_get_tex_format(image->vk_format);

//       //   if (!rsc->tiled) {
//       //           if (prsc->nr_samples > 1) {
//       //                   return ~0;
//       //           } else {
//       //                   if (format == VC4_TEXTURE_TYPE_RGBA8888)
//       //                           return VC4_TEXTURE_TYPE_RGBA32R;
//       //                   else
//       //                           return ~0;
//       //           }
//       //   }

//         return format;
// }

static VkFormatFeatureFlags
image_format_features(VkFormat vk_format,
                      const struct vc4_format *vc4_format,
                      VkImageTiling tiling)
{
   if (!vc4_format || !vc4_format->supported)
      return 0;

   const VkImageAspectFlags aspects = vk_format_aspects(vk_format);

   const VkImageAspectFlags zs_aspects = VK_IMAGE_ASPECT_DEPTH_BIT |
                                         VK_IMAGE_ASPECT_STENCIL_BIT;
   const VkImageAspectFlags supported_aspects = VK_IMAGE_ASPECT_COLOR_BIT |
                                                zs_aspects;
   if ((aspects & supported_aspects) != aspects)
      return 0;

   /* FIXME: We don't support separate stencil yet */
   if ((aspects & zs_aspects) == VK_IMAGE_ASPECT_STENCIL_BIT)
      return 0;

   if (vc4_format->tex_type == TEXTURE_DATA_FORMAT_NO &&
       vc4_format->rt_type == V3D_OUTPUT_IMAGE_FORMAT_NO) {
      return 0;
   }

   VkFormatFeatureFlags flags = 0;

   /* Raster format is only supported for 1D textures, so let's just
    * always require optimal tiling for anything that requires sampling.
    * Note: even if the user requests optimal for a 1D image, we will still
    * use raster format since that is what the HW requires.
    */
   if (vc4_format->tex_type != TEXTURE_DATA_FORMAT_NO &&
       tiling == VK_IMAGE_TILING_OPTIMAL) {
      flags |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
               VK_FORMAT_FEATURE_BLIT_SRC_BIT;

//       if (vc4_format->supports_filtering)
//          flags |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
   }

   if (vc4_format->rt_type != V3D_OUTPUT_IMAGE_FORMAT_NO) {
      if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
         flags |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT |
                  VK_FORMAT_FEATURE_BLIT_DST_BIT;
        //  if (format_supports_blending(vc4_format))
        //     flags |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT;
      } else if (aspects & zs_aspects) {
         flags |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT |
                  VK_FORMAT_FEATURE_BLIT_DST_BIT;
      }
   }

   const struct util_format_description *desc =
      vk_format_description(vk_format);
   assert(desc);

   if (desc->layout == UTIL_FORMAT_LAYOUT_PLAIN && desc->is_array) {
      flags |= VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT;
      if (desc->nr_channels == 1 && vk_format_is_int(vk_format))
         flags |= VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT;
   }

   if (flags) {
      flags |= VK_FORMAT_FEATURE_TRANSFER_SRC_BIT |
               VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
   }

   return flags;
}

static VkFormatFeatureFlags
buffer_format_features(VkFormat vk_format, const struct vc4_format *vc4_format)
{
   if (!vc4_format || !vc4_format->supported)
      return 0;

   if (!vc4_format->supported)
      return 0;

   /* We probably only want to support buffer formats that have a
    * color format specification.
    */
   if (!vk_format_is_color(vk_format))
      return 0;

   const struct util_format_description *desc =
      vk_format_description(vk_format);
   assert(desc);

   VkFormatFeatureFlags flags = 0;
   if (desc->layout == UTIL_FORMAT_LAYOUT_PLAIN &&
       desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB &&
       desc->is_array) {
      flags |=  VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT;
      if (vc4_format->tex_type != TEXTURE_DATA_FORMAT_NO) {
         flags |= VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT |
                  VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT;
      }
   } else if (vk_format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) {
      flags |= VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT |
               VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT;
   } else if (vk_format == VK_FORMAT_A2B10G10R10_UINT_PACK32 ||
              vk_format == VK_FORMAT_B10G11R11_UFLOAT_PACK32) {
      flags |= VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT;
   }

   if (desc->layout == UTIL_FORMAT_LAYOUT_PLAIN &&
       desc->is_array &&
       desc->nr_channels == 1 &&
       vk_format_is_int(vk_format)) {
      flags |= VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT;
   }

   return flags;
}

void
vc4_GetPhysicalDeviceFormatProperties(VkPhysicalDevice physicalDevice,
                                       VkFormat format,
                                       VkFormatProperties* pFormatProperties)
{
   const struct vc4_format *vc4_format = vc4_get_format(format);

   *pFormatProperties = (VkFormatProperties) {
      .linearTilingFeatures =
         image_format_features(format, vc4_format, VK_IMAGE_TILING_LINEAR),
      .optimalTilingFeatures =
         image_format_features(format, vc4_format, VK_IMAGE_TILING_OPTIMAL),
      .bufferFeatures =
         buffer_format_features(format, vc4_format),
   };
}

void
vc4_GetPhysicalDeviceFormatProperties2(
    VkPhysicalDevice physicalDevice,
    VkFormat format,
    VkFormatProperties2 *pFormatProperties)
{
   // VC4_FROM_HANDLE(vc4_physical_device, physical_device, physicalDevice);

   vc4_GetPhysicalDeviceFormatProperties(physicalDevice, format,
                                         &pFormatProperties->formatProperties);

   VkDrmFormatModifierPropertiesListEXT *list =
       vk_find_struct(pFormatProperties->pNext, DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT);
   if (list) {
      VK_OUTARRAY_MAKE(out, list->pDrmFormatModifierProperties,
                       &list->drmFormatModifierCount);

      vk_outarray_append(&out, mod_props)
      {
         mod_props->drmFormatModifier = DRM_FORMAT_MOD_LINEAR;
         mod_props->drmFormatModifierPlaneCount = 1;
      }

      /* TODO: any cases where this should be disabled? */
      vk_outarray_append(&out, mod_props)
      {
         mod_props->drmFormatModifier = DRM_FORMAT_MOD_BROADCOM_VC4_T_TILED;
         mod_props->drmFormatModifierPlaneCount = 1;
      }
   }
}

VkResult
vc4_GetPhysicalDeviceImageFormatProperties(
   VkPhysicalDevice physicalDevice,
   VkFormat format,
   VkImageType type,
   VkImageTiling tiling,
   VkImageUsageFlags usage,
   VkImageCreateFlags createFlags,
   VkImageFormatProperties *pImageFormatProperties)
{
//    VC4_FROM_HANDLE(vc4_physical_device, physical_device, physicalDevice);

//    const VkPhysicalDeviceImageFormatInfo2 info = {
//       .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
//       .pNext = NULL,
//       .format = format,
//       .type = type,
//       .tiling = tiling,
//       .usage = usage,
//       .flags = createFlags,
//    };

//    return vc4_get_image_format_properties(physical_device, &info,
//                                          pImageFormatProperties, NULL);
    return VK_SUCCESS;
}

void
vc4_GetPhysicalDeviceSparseImageFormatProperties(
   VkPhysicalDevice physicalDevice,
   VkFormat format,
   VkImageType type,
   uint32_t samples,
   VkImageUsageFlags usage,
   VkImageTiling tiling,
   uint32_t *pNumProperties,
   VkSparseImageFormatProperties *pProperties)
{
   /* Sparse images are not yet supported. */
   *pNumProperties = 0;
}